<template>
  <div class="profile-page">
    <div class="page-header">
      <h2>个人信息</h2>
    </div>

    <el-row :gutter="20">
      <!-- 个人信息卡片 -->
      <el-col :span="8">
        <el-card class="profile-card">
          <div class="profile-header">
            <el-upload
              class="avatar-uploader"
              action="/api/upload"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :on-success="handleAvatarSuccess"
            >
              <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <h3>{{ userInfo.username }}</h3>
            <p>{{ userInfo.role }}</p>
          </div>
          
          <el-divider />
          
          <div class="profile-info">
            <p><el-icon><Message /></el-icon> {{ userInfo.email || '未设置邮箱' }}</p>
            <p><el-icon><Phone /></el-icon> {{ userInfo.phone || '未设置手机' }}</p>
            <p><el-icon><Calendar /></el-icon> 注册时间：{{ formatDate(userInfo.createdAt) }}</p>
          </div>
        </el-card>
      </el-col>

      <!-- 信息编辑表单 -->
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>编辑个人信息</span>
            </div>
          </template>

          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="100px"
            class="profile-form"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" />
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" />
            </el-form-item>

            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="form.phone" />
            </el-form-item>

            <el-divider>修改密码</el-divider>

            <el-form-item label="当前密码" prop="currentPassword">
              <el-input
                v-model="form.currentPassword"
                type="password"
                show-password
                placeholder="如需修改密码请输入当前密码"
              />
            </el-form-item>

            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="form.newPassword"
                type="password"
                show-password
                placeholder="请输入新密码"
              />
            </el-form-item>

            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="form.confirmPassword"
                type="password"
                show-password
                placeholder="请再次输入新密码"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleSubmit">保存更改</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 安全设置卡片 -->
        <el-card class="security-card">
          <template #header>
            <div class="card-header">
              <span>安全设置</span>
            </div>
          </template>

          <div class="security-settings">
            <div class="security-item">
              <div class="security-info">
                <h4>双因素认证</h4>
                <p>启用双因素认证以增强账户安全性</p>
              </div>
              <el-switch v-model="securitySettings.twoFactor" />
            </div>

            <el-divider />

            <div class="security-item">
              <div class="security-info">
                <h4>登录通知</h4>
                <p>当有新的登录活动时通过邮件通知</p>
              </div>
              <el-switch v-model="securitySettings.loginNotification" />
            </div>

            <el-divider />

            <div class="security-item">
              <div class="security-info">
                <h4>异地登录验证</h4>
                <p>在新设备或异地登录时需要验证</p>
              </div>
              <el-switch v-model="securitySettings.locationCheck" />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Message, Phone, Calendar } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()

// 用户信息
const userInfo = reactive({
  username: 'Admin',
  role: '系统管理员',
  email: 'admin@example.com',
  phone: '',
  avatar: '',
  createdAt: new Date()
})

// 表单数据
const form = reactive({
  username: userInfo.username,
  email: userInfo.email,
  phone: userInfo.phone,
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 安全设置
const securitySettings = reactive({
  twoFactor: false,
  loginNotification: true,
  locationCheck: true
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  newPassword: [
    { min: 6, message: '密码长度不能小于 6 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    {
      validator: (rule, value, callback) => {
        if (form.newPassword && value !== form.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

// 头像上传前的验证
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传头像图片只能是图片格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 头像上传成功的回调
const handleAvatarSuccess = (response) => {
  userInfo.avatar = response.url
  ElMessage.success('头像上传成功')
}

// 表单提交
const formRef = ref(null)
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 这里应该调用API更新用户信息
    console.log('提交的表单数据:', form)
    
    ElMessage.success('个人信息更新成功')
    
    // 如果更改了密码，可能需要重新登录
    if (form.newPassword) {
      authStore.logout()
      router.push('/login')
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}
</script>

<style scoped>
.profile-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-weight: 600;
}

.profile-card {
  text-align: center;
}

.profile-header {
  margin-bottom: 20px;
}

.avatar-uploader {
  margin-bottom: 20px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  display: block;
}

.profile-info {
  text-align: left;
}

.profile-info p {
  margin: 10px 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.security-card {
  margin-top: 20px;
}

.security-settings {
  .security-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;

    .security-info {
      h4 {
        margin: 0;
        font-size: 16px;
      }

      p {
        margin: 5px 0 0;
        color: #666;
        font-size: 14px;
      }
    }
  }
}

.el-divider {
  margin: 16px 0;
}
</style>